<template>
  <div class="doc">
    <a-button type="primary" class="btnAdd" @click="showAdd">新增</a-button>
    <a-table
      :dataSource="docs"
      :columns="columns"
      :row-key="(record:Doc)=>record.id"
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.title === 'Action'">
          <a-button type="primary" @click="showEdit(record)">编辑</a-button>
          <a-popconfirm
            title="确定删除该文档？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="confirm($event, record)"
          >
            <a-button type="primary" danger class="btnDel"> 删除 </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 编辑modal -->
    <a-modal v-model:visible="visible" :title="modalTitle" @ok="handleEdit_Add">
      <a-form
        :model="formState"
        name="basic"
        :rules="rules"
        :labelCol="{ span: 4 }"
        autocomplete="off"
      >
        <a-form-item label="名称" name="name">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="父文档" name="parent">
          <a-tree-select
            v-model:value="formState.parent"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择父文档"
            tree-default-expand-all
            :field-names="{ children: 'children', label: 'name', value: 'id' }"
            :tree-data="level1"
          >
          </a-tree-select>
        </a-form-item>
        <a-form-item label="顺序" name="sort">
          <a-input v-model:value="formState.sort" />
        </a-form-item>
        <a-form-item label="内容" name="content">
          <!-- 富文本编辑器 挂载点-->
          <div id="richText"></div>
        </a-form-item>
        <a-button
          type="primary"
          class="previewBtn"
          @click="visiblePreview = true"
        >
          <template #icon><eye-outlined /></template>
          内容预览
        </a-button>
      </a-form>
    </a-modal>

    <!-- 内容预览 -->
    <a-drawer
      v-model:visible="visiblePreview"
      class="custom-class"
      placement="right"
      width="478"
    >
      <!-- 内容 -->
      <div :innerHTML="formState.content"></div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import {
  getDocListByPage,
  editDoc,
  removeDoc,
  findContentById,
} from "@/api/doc";
import { toTreeDoc, getDocLevel1 } from "@/util/toTree";
import { Form, message } from "ant-design-vue";
import { setDisable, clearDisable } from "@/util/tools";
import E from "wangeditor";
import { useRoute } from "vue-router";

const useForm = Form.useForm;
let route = useRoute();
// table
let columns = reactive([
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "父文档",
    dataIndex: "parent",
  },
  {
    title: "顺序",
    dataIndex: "sort",
  },
  {
    title: "Action",
    dataIndex: "axtion",
  },
]);
interface Doc {
  ebook_id: number;
  id: number;
  name: string;
  parent: number;
  sort: number;
  view_count: number;
  vote_count: number;
  children?: Doc[];
}
let docs = reactive<Doc[]>([
  //   {
  //     ebook_id: 1,
  //     id: 1,
  //     name: "1",
  //     parent: 1,
  //     sort: 1,
  //     view_count: 0,
  //     vote_count: 0,
  //     children: [{ name: "1", parent: "1", sort: 2 }],
  //   },
]);
let loading = ref(false);
// level1
let level1 = reactive<any[]>([]);
const contentList = reactive<any>({});
// =========================== 根据id获取内容
const getContentList = (docs: any) => {
  let ids = docs.map((item: any) => {
    return item.id;
  });
  ids.forEach((id: number) => {
    findContentById(id).then((res) => {
      contentList[id] = res.data.data;
    });
  });
};
// =========================== 初始化数据
const handlerQuery = () => {
  loading.value = true;
  getDocListByPage(route.params.ebookId).then((res) => {
    let docsTree = toTreeDoc(res.data.data);
    docs.length = 0;
    docs.push(...docsTree);

    // level1
    level1.length = 0;
    level1.push(...getDocLevel1(res.data.data));

    // console.log(res.data.data);
    // 获取content
    getContentList(res.data.data);

    loading.value = false;
  });
};
handlerQuery();

// =========================== 表单
const modalTitle = ref<string>("");
const visible = ref<boolean>(false);
let formState = reactive<any>({
  ebook_id: 0,
  id: 0,
  name: "",
  parent: 0,
  sort: 0,
  content: "",
});
const rules = reactive({
  name: [{ required: true, message: "不为空", trigger: "blur" }],
  parent: [{ required: true, message: "不为空", trigger: "blur" }],
  sort: [{ required: true, message: "不为空", trigger: "blur" }],
  content: [{ required: true, message: "不为空", trigger: "blur" }],
});
// 验证
const { resetFields, validate, validateInfos } = useForm(formState, rules);

// =========================== 删除
const confirm = (e: any, record: any) => {
  // console.log(record.id);

  removeDoc(record.id).then((res) => {
    // console.log(res);

    if (res.data.code === 10001) {
      message.success("删除成功");
      handlerQuery();
      return;
    }
    message.error("删除失败");
  });
};
// =========================== 编辑 | 添加
const editor = new E("#richText"); //富文本
editor.config.onchange = (html: any) => {
  //更改赋值
  formState.content = html;
};
const visiblePreview = ref<boolean>(false); //内容预览
const showEdit = (record: any) => {
  modalTitle.value = "编辑文档";
  visible.value = true;
  editor.txt.html("");

  //   显示数据(content另外的接口)
  Object.keys(formState).forEach((key) => {
    if (key != "content") formState[key] = record[key];
  });

  // 设置为disabled
  setDisable(level1, record.id);

  //
  setTimeout(() => {
    try {
      editor.create();
    } catch (err) {}

    // 初始化content
    editor.txt.html(contentList[record.id]);
  }, 100);
};
const showAdd = (record: any) => {
  clearDisable(level1);

  modalTitle.value = "添加文档";
  visible.value = true;

  // 清空数据
  resetFields();
  editor.txt.html("");

  // 设置ebookid
  formState.ebook_id = route.params.ebookId;

  //
  setTimeout(() => {
    try {
      editor.create();
    } catch (err) {}
  }, 100);
};
const handleEdit_Add = () => {
  //
  validate().then((_) => {
    if (modalTitle.value === "编辑文档") {
      return editDoc(formState).then((res) => {
        if (res.data.code === 10001) {
          message.success("编辑成功");
          // 关闭显示
          visible.value = false;
          // 刷新数据
          handlerQuery();
          return;
        }
        message.error("编辑失败");
      });
    }
    editDoc(formState).then((res) => {
      // console.log("添加：", formState);

      if (res.data.code === 10001) {
        message.success("添加成功");
        // 关闭显示
        visible.value = false;
        // 刷新数据
        handlerQuery();
        return;
      }
      message.error("添加失败");
    });
  });
};
</script>

<style scope>
.btnAdd {
  margin-bottom: 10px;
}
.doc {
  padding: 24px;
}
.btnDel {
  margin-left: 10px;
}
.previewBtn {
  position: absolute;
  bottom: 60px;
  right: 16px;
}
</style>
